#!/bin/bash

# 定义错误处理函数
function my_error_handler {
    echo "An error occurred in function '$1' on line $2. Exiting..."
    exit 1
}

# 捕捉函数内部的 ERR 信号
function my_function {
    set -euo pipefail
    trap 'my_error_handler my_function $LINENO' ERR
    
    echo "Starting my_function..."

    # 使用未定义的变量会导致函数退出
    echo $UNDEFINED_VAR

    # 如果某个命令失败，函数会立即退出
    ls /nonexistent_directory

    echo "This line will not be executed if there is an error."
}

# 调用函数
my_function

echo "This line will not be executed if my_function fails."